package servlets;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.*;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Text;

import domain.Team;
import utils.Tools;

@SuppressWarnings("serial")
public class FetchTeamsPlayersServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		SAXBuilder sxb = new SAXBuilder();
		List<Team> a_teams = new ArrayList<Team>();
		try {
			String url = "http://api.sportsdatallc.org/nhl-t3/league/hierarchy.xml?api_key=9hudh47adxxjrezrd4tkuzpx";
			Document doc = sxb.build(new URL(url));
			Element racine = doc.getRootElement();
			List<Element> conferences = racine.getChildren();
			for (Element c : conferences) {
				
				List<Element> divisions = c.getChildren();
				System.out.println("conference : " + c.getAttributeValue("name"));
				for (Element e : divisions) {

					List<Element> teams = e.getChildren();
					System.out.println("\tdivision : "
							+ e.getAttributeValue("name"));
					for (Element t : teams) {
						
						Element v = t.getChildren().get(0);
						
						System.out.println("\t\t" + t.getAttributeValue("name"));
						a_teams.add(new Team(
								c.getAttributeValue("name"),
								e.getAttributeValue("name"),
								t.getAttributeValue("id"), 
								t.getAttributeValue("name"), 
								t.getAttributeValue("market"), 
								t.getAttributeValue("alias"), 
								v.getAttributeValue("id"), 
								v.getAttributeValue("name"), 
								v.getAttributeValue("capacity"), 
								v.getAttributeValue("address"), 
								v.getAttributeValue("city"), 
								v.getAttributeValue("state"), 
								v.getAttributeValue("zip"), 
								v.getAttributeValue("country")
							));

					}

				}
			}

			Thread.sleep(1000);

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		SAXBuilder sxb_deux = new SAXBuilder();
		Calendar cal = Calendar.getInstance();
		
		for(Team t : a_teams) {
			
			String id = t.getId();
			
			String url = "http://api.sportsdatallc.org/nhl-t3/seasontd/"
					//+ cal.get(Calendar.YEAR) +
					+ "2013" + 
					"/reg/teams/"
					+ id +
					"/statistics.xml?api_key=h7n5d5fxyr6eghf7qftfmpg2";
			try {
				
				Document doc = sxb_deux.build(new URL(url));
				Element racine = doc.getRootElement();
				
				Element total = racine.getChildren().get(0).getChildren().get(0).getChildren().get(0).getChildren().get(0).getChildren().get(0);
				System.out.println(total.getAttributeValue("games_played"));
				Element powerplay = total.getChildren().get(0);
				Element shorthanded = total.getChildren().get(1);
				Element evenstrength = total.getChildren().get(2);
				
				Element players = racine.getChildren().get(0).getChildren().get(1);
				
				System.out.println(Math.floor(Double.parseDouble(shorthanded.getAttributeValue("faceoff_win_pct"))));
				
				Entity team = new Entity("Team", id);
				
				team.setProperty("id", id);
				team.setProperty("conference", t.getConference());
				team.setProperty("division", t.getDivision());
				
				team.setProperty("name", t.getName());
				team.setProperty("market", t.getMarket());
				team.setProperty("alias", t.getAlias());
				team.setProperty("v_id", t.getV_id());
				team.setProperty("v_name", t.getV_name());
				team.setProperty("v_capacity", Integer.parseInt(t.getV_capacity()));
				team.setProperty("v_address", t.getV_address());
				team.setProperty("v_city", t.getV_city());
				team.setProperty("v_state", t.getV_state());
				team.setProperty("v_zip", t.getV_zip());
				team.setProperty("v_country", t.getV_country());
				
				team.setProperty("games_played", Integer.parseInt(total.getAttributeValue("games_played")));
				team.setProperty("goals", Integer.parseInt(total.getAttributeValue("goals")));
				team.setProperty("points", Math.floor(Double.parseDouble(shorthanded.getAttributeValue("faceoff_win_pct"))));
				
				String splayers = "[";
				
				for(Element p : players.getChildren()) {
					
					splayers += "{\"id\":\"" +
					p.getAttributeValue("id") +
					"\", \"full_name\":\"" +
					p.getAttributeValue("full_name") +
					"\", \"first_name\":\"" +
					p.getAttributeValue("first_name") +
					"\", \"last_name\":\"" +
					p.getAttributeValue("last_name") +
					"\", \"position\":\"" +
					p.getAttributeValue("position")  +
					"\", \"primary_position\":\"" +
					p.getAttributeValue("primary_position")  +
					"\", \"jersey_number\":\"" +
					p.getAttributeValue("jersey_number") +
					"\"}, ";
					
				}
				
				splayers = splayers.substring(0, splayers.length() - 2);
				splayers += "]";
				
				team.setProperty("joueurs", new Text(splayers));
				
				datastore.put(team);
				
				Thread.sleep(1000);
				
			} catch (JDOMException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
}
